package com.app.shop.service.shop.impl;


import com.app.shop.dao.wg.WgCommodityMapper;
import com.app.shop.dao.wg.WgOrderMapper;
import com.app.shop.dao.wg.WgOrderstatuslogMapper;
import com.app.shop.dao.wg.WgTransactionMapper;
import com.app.shop.entity.*;
import com.app.shop.entity.query.WgOrderQuery;
import com.app.shop.enums.DeleteEnum;
import com.app.shop.enums.OrderStatusEnum;
import com.app.shop.enums.TransactionStatusEnum;
import com.app.shop.service.shop.WgOrderService;
import com.app.shop.service.shop.WgOrderService;
import com.app.shop.util.DateUtil;
import com.app.shop.util.OrderCodeUtils;
import com.app.shop.util.SysModel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;


/**
 * 订单服务
 *
 * @author chenliwei
 * @version v1.0 2019-3-11
 */
@Service("wgOrderService")
public class WgOrderServiceImp implements WgOrderService {

    private static final Logger log = LoggerFactory.getLogger(WgOrderServiceImp.class);

    @Autowired
    private WgOrderMapper wgOrderMapper;

    @Autowired
    private WgTransactionMapper wgTransactionMapper;

    @Autowired
    private WgOrderstatuslogMapper orderstatuslogMapper;

    @Autowired
    private WgCommodityMapper wgCommodityMapper;


    @Override
    public Page<WgOrder> getWgOrderList(WgOrderQuery wgOrderQuery) {
        //查询条件
        WgOrderExample sysMenuExample = new WgOrderExample();
        WgOrderExample.Criteria criteria = sysMenuExample.createCriteria();
        //商品单号
        if (wgOrderQuery.getOrderCode() != null && wgOrderQuery.getOrderCode().trim().length() > 0) {
            criteria.andOrderCodeLike('%' + wgOrderQuery.getOrderCode() + '%');
        }
        //商品名称
        if (wgOrderQuery.getCommodityId() != null ) {
            criteria.andCommodityIdEqualTo(wgOrderQuery.getCommodityId());
        }
        //用户姓名
        if (wgOrderQuery.getUsername() != null && wgOrderQuery.getUsername().trim().length() > 0) {
            criteria.andOrderCodeLike('%' + wgOrderQuery.getOrderCode() + '%');
        }
        //用户手机号
        if (wgOrderQuery.getPhone() != null && wgOrderQuery.getPhone().trim().length() > 0) {
            criteria.andOrderCodeLike('%' + wgOrderQuery.getOrderCode() + '%');
        }
        //订单支付状态
        if (wgOrderQuery.getStatus() != null ) {
            criteria.andStatusEqualTo(wgOrderQuery.getStatus());
        }
        //订单有效/失效状态（平台退单）
        if (wgOrderQuery.getDeleteflag() != null) {
            criteria.andDeleteFlagEqualTo(wgOrderQuery.getDeleteflag());
        }
        //模拟分页查询
        PageHelper.startPage(wgOrderQuery.getCurrentPage(), wgOrderQuery.getPageSize());
        return wgOrderMapper.selectByExample(sysMenuExample);
    }

    @Override
    public void saveTransaction(Integer orderId, String price, Integer payType, String payCode) throws Exception {

        WgOrder order =wgOrderMapper.selectByPrimaryKey(orderId);
        BigDecimal priceValueBigDecimal = BigDecimal.valueOf(Double
                .valueOf(price));
        if (price != null && Double.valueOf(price) < 0) {
            log.debug("Making the price Zero since the amount is negative");
            priceValueBigDecimal = BigDecimal.ZERO;
        }
        WgTransaction wgTransaction =new WgTransaction();

        //wgTransaction=wgTransactionMapper.getpayCallBackTransactionInfo(orderId);
        //查询条件
        WgTransactionExample wgTransactionExample = new WgTransactionExample();
        WgTransactionExample.Criteria criteria = wgTransactionExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        wgTransaction=wgTransactionMapper.selectByExampleByOrder(wgTransactionExample);
        if(wgTransaction!=null){
            WgTransaction newWgTransaction = new WgTransaction();
            newWgTransaction.setId(wgTransaction.getId());
            newWgTransaction.setOrderId(orderId);
            newWgTransaction.setPayCallBack("T");
            newWgTransaction.setStatus(TransactionStatusEnum.SUCCESS.value());
            newWgTransaction.setAmount(priceValueBigDecimal);
            newWgTransaction.setPayType(payType);
            newWgTransaction.setModifiedUserId(order.getMemberId());
            newWgTransaction.setModifiedDate(DateUtil.getNow());
            wgTransactionMapper.updateByPrimaryKeySelective(newWgTransaction);
        }else{
            WgTransaction insertTransactionHistory = new WgTransaction();
            insertTransactionHistory.setOrderId(Integer.valueOf(orderId));
            insertTransactionHistory.setAmount(priceValueBigDecimal);
            insertTransactionHistory.setPayType(payType);
            insertTransactionHistory.setStatus(TransactionStatusEnum.SUCCESS.value());
            insertTransactionHistory.setPayCode(payCode);
            insertTransactionHistory.setPayCallBack("F");
            insertTransactionHistory.setDeleteFlag(DeleteEnum.NORMAL.value());
            insertTransactionHistory.setCreatedUserId(order.getMemberId());
            insertTransactionHistory.setCreatedDate(DateUtil.getNow());
            wgTransactionMapper.insertSelective(insertTransactionHistory);

        }

        log.debug("saveTransaction end");

    }

    @Override
    public void paySuccess(WgOrder order, String price, String alipayCode) throws Exception {
        if(!OrderStatusEnum.NOTPAYORDER_STATUS_ENUM.equals(order.getStatus())){
            return;
        }
        updateOrderStatus(order.getMemberId(),order.getId(),OrderStatusEnum.PAYEDORDER_STATUS_ENUM);
        log.debug("paySuccess end");
    }

    @Override
    public void updateOrderStatus(Integer userId, Integer orderId, OrderStatusEnum statusEnum) throws Exception {
        WgOrder order = wgOrderMapper.selectByPrimaryKey(orderId);
        if(null==order){
            throw new Exception("订单不存在");
        }
        order.setStatus(statusEnum.value());
        order.setModifiedUserId(userId);
        order.setModifiedDate(DateUtil.getNow());
        addOrderStatusHistory(userId,order);
        wgOrderMapper.updateByPrimaryKeySelective(order);




    }


    @Override
    public WgOrder insertOrderInfo(Integer userId, Integer comId,String phone, String name) throws Exception {
        WgCommodity wgCommodity =wgCommodityMapper.selectByPrimaryKey(comId);
        WgOrder wgOrder = new WgOrder();
        wgOrder.setMemberId(userId);
        wgOrder.setCommodityId(comId);
        wgOrder.setPayPrice(wgCommodity.getPrice());
        wgOrder.setBuyNum(1);
//        wgOrder.setStatus(OrderStatusEnum.NOTPAYORDER_STATUS_ENUM.value());
        wgOrder.setOrderTime(DateUtil.getNow());
        wgOrder.setPhone(phone);
        wgOrder.setUsername(name);
        wgOrder.setDeleteFlag(DeleteEnum.NORMAL.value());
        wgOrder.setClientDeleteFlag(DeleteEnum.NORMAL.value());
        wgOrder.setCreateUserId(userId);
        wgOrder.setCreatedDate(DateUtil.getNow());
        wgOrderMapper.insertSelective(wgOrder);
        Integer orderKey=wgOrder.getId();
        updateOrderStatus(userId,orderKey,OrderStatusEnum.NOTPAYORDER_STATUS_ENUM);
        String orderCode= OrderCodeUtils.getOrderCode(1,orderKey);
        WgOrder updateOrderCode = new WgOrder();
        updateOrderCode.setId(orderKey);
        updateOrderCode.setOrderCode(orderCode);
        wgOrderMapper.updateByPrimaryKeySelective(updateOrderCode);
        return wgOrderMapper.selectByPrimaryKey(orderKey);
    }


    /**
     * @Title
     * @Description (添加订单历史状态变更记录)
     * @author Garfield Miao
     * @date 2019年25月07日
     * @upAuthor Garfield Miao
     * @update 2019年25月07日 
     */
    private void addOrderStatusHistory(int userId,WgOrder order){

        WgOrderstatuslog orderStatusLog = new WgOrderstatuslog();
        orderStatusLog.setCreatedby(userId);
        orderStatusLog.setCreateddate(DateUtil.getNow());
        orderStatusLog.setModifiedby(userId);
        orderStatusLog.setModifieddate(DateUtil.getNow());
        orderStatusLog.setDeleteflag(DeleteEnum.NORMAL.value());
        orderStatusLog.setOrderid(order.getId());
        orderStatusLog.setStatus(order.getStatus());
        orderstatuslogMapper.insertSelective(orderStatusLog);
    }



}
